package com.hm.health.Activity.ecgflash;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.fragment.app.Fragment;

import com.goodix.comsdk.RomaDevice;
import com.goodix.libromablecom.sdk.cardiff.CardiffConstants;
import com.goodix.libromablecom.sdk.cardiff.CardiffDeviceController;
import com.goodix.libromablecom.sdk.cardiff.arguments.SetArgumentsKeyEnum;
import com.goodix.libromablecom.sdk.cardiff.arguments.StartArgumentsKeyEnum;
import com.goodix.utils.SPUtils;
import com.goodix.utils.ToastUtils;
import com.goodix.widget.AlertDialogEx;

import com.google.gson.reflect.TypeToken;
import com.hm.health.Activity.BaseActivity;
import com.hm.health.Activity.HomeActivity;
import com.hm.health.Fragment.ECGChartFragment;
import com.hm.health.Fragment.LineChartFragment;
import com.hm.health.Fragment.MeasureResultFragment;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.entity.BleDevicesInfo;
import com.hm.health.entity.CheckBoxProperty;
import com.hm.health.entity.arguments.StartArgumentsManager;
import com.hm.health.service.EcgFlashService;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class EcgFlashOnlineActivity extends BaseActivity {

    public static final String TAG = "EcgFlashOnlineActivity";

    @BindView(R.id.demo_continued_time)
    TextView mContinuedTimeView;

    private static final int[] COLORS = {R.color.curvecolor1, R.color.curvecolor2, R.color.curvecolor3,
            R.color.curvecolor4, R.color.curvecolor5, R.color.curvecolor6,
            R.color.curvecolor7, R.color.curvecolor8, R.color.curvecolor9, R.color.curvecolor10};

    private String mFunctionName;
    private List<BleDevicesInfo> mDeviceInfos = new ArrayList<>();
    // 是否为单次测量
    private int mMeasurementMode = StartArgumentsKeyEnum.CONTINUOUS_MEASUREMENT;
    private EcgFlashService.EcgFlashBinder mBinder;
    private ServiceConnection mServiceConnection;

    public static boolean mIsFront = false;

    @Override
    public void onBackPressed() {
        ToastUtils.showShortToastMessage(mContext, getString(R.string.tips_exit_test));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hbd_test);
        ButterKnife.bind(this);
        initArguments();
        initActionBar();
        startTestRecorder();
        mIsFront = true;
    }

    private void startTestRecorder() {

        // 初始化测量设备列表
        // Goodix 设备
        RomaDevice device = MyApplication.getHBDTestClient().getRomaDevice();
        BleDevicesInfo devicesInfo = new BleDevicesInfo(device.getDeviceName(),
                device.getDeviceAddress());
        mDeviceInfos.add(devicesInfo);

        // 对比设备
        List<BleDevicesInfo> devicesInfos = SPUtils.getJsonObj(mContext,
                HomeActivity.KEY_BLE_COMPARE_DEVICES_INFO, new ArrayList<>(),
                new TypeToken<List<BleDevicesInfo>>(){}.getType());
        mDeviceInfos.addAll(devicesInfos);

        // 从服务获取时间信息
        mServiceConnection = new ServiceConnection(){
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.d(TAG, "onServiceConnected");
                mBinder = (EcgFlashService.EcgFlashBinder) iBinder;
                if (mBinder != null) {
                    mBinder.registerEcgFlashCallback(mServiceCallback);
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.d(TAG, "onServiceDisconnected");
                mBinder.unregisterEcgFlashCallback(mServiceCallback);
                mBinder = null;
            }
        };

        Intent intent = new Intent(mContext, EcgFlashService.class);
        bindService(intent, mServiceConnection, Service.BIND_AUTO_CREATE);


        // 更新测量结果Fragment
        replaceFragment(R.id.view_measure_result,
                MeasureResultFragment.newInstance(mFunctionName, mDeviceInfos),
                false);

        initLineChartFragment();
    }

    private void initArguments() {
        mMeasurementMode = StartArgumentsManager.getInstance().getMeasurementMode();
        mFunctionName = StartArgumentsManager.getInstance().getFunctionName();
        if (mFunctionName == null || mFunctionName.isEmpty()) {
            AlertDialogEx.Builder builder = new AlertDialogEx.Builder(mContext);
            builder.setMessage(getString(R.string.no_valid_function_name));
            builder.setPositiveButton(R.string.quit, view -> finish());
            builder.show();
        }
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (null != actionBar) {
            actionBar.setDisplayHomeAsUpEnabled(false);
            actionBar.setHomeButtonEnabled(false);
            setCenterTitle(mFunctionName);
        }
    }

    private void initLineChartFragment() {
        List<CheckBoxProperty> checkBoxProperties = new ArrayList<>();
        int[] selected = new int[128];
        CardiffDeviceController.getInstance().getDefaultSelectChannel("0", selected);
        String header = CardiffDeviceController.getInstance().getFileHeader(mFunctionName);
        String[] cols = header.split(",");
        cols = Arrays.copyOfRange(cols, 1, cols.length);
        int cnt = 0;
        List<Integer> selecteds = new ArrayList<>();
        try {
            for (int i = 0; i < cols.length - 1; ++i) {

                // bit 1 show or not
                if ((selected[i] & 2) != 2) {
                    continue;
                }

                // bit 0 select or not
                if ((selected[i] & 1) == 1) {
                    selecteds.add(cnt);
                }

                int checkedColor = getResources().getColor(COLORS[i % COLORS.length]);
                CheckBoxProperty property = new CheckBoxProperty(checkedColor, R.color.gray,
                        cols[i], false, i);
                checkBoxProperties.add(property);
                cnt++;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            ToastUtils.showShortToastMessage(mContext, e.getMessage());
        }

        findViewById(R.id.fl_line_chart1).setVisibility(View.VISIBLE);
        if (selecteds.size() > 0) {
            checkBoxProperties.get(selecteds.get(0)).setChecked(true);
        }
        replaceFragment(R.id.fl_line_chart,
                LineChartFragment.newInstance(mFunctionName, checkBoxProperties),
                false);
        if (selecteds.size() > 1) {
            checkBoxProperties.get(selecteds.get(0)).setChecked(false);
            checkBoxProperties.get(selecteds.get(1)).setChecked(true);
        }

        Fragment fragment;
        if (mFunctionName.toUpperCase().contains(StartArgumentsKeyEnum.AppFunction_ECG)) {
            fragment = ECGChartFragment.newInstance(mFunctionName);
        }  else {
            fragment = LineChartFragment.newInstance(mFunctionName, checkBoxProperties);
        }
        replaceFragment(R.id.fl_line_chart1, fragment, false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.cardiff_demo, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.quit) {
            onActionStop();
        }
        return super.onOptionsItemSelected(item);
    }


    public void onActionStop() {
        AlertDialogEx.Builder builder = new AlertDialogEx.Builder(mContext);
        builder.setMessage(R.string.ecg_flash_whether_stop_test);
        builder.setPositiveButton(R.string.quit, view -> {
            finish();
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy");
        MyApplication.getHBDTestClient().setRunTimeFlag(SetArgumentsKeyEnum.ARG_READ_SAMPLE_DATA,
                CardiffConstants.CARDIFF_DATA_OFFLINE_ARG);
        unbindService(mServiceConnection);
        mIsFront = false;
        super.onDestroy();
    }

    private void updateTimeOnUIThread(String time) {
        runOnUiThread(() -> {
            mContinuedTimeView.setText(time);
        });
    }

    private EcgFlashService.IEcgFlashServiceCallback mServiceCallback =  new EcgFlashService.IEcgFlashServiceCallback() {
        @Override
        public void onTimeUpdate(String time) {
            updateTimeOnUIThread(time);
        }

        @Override
        public void onStatusChanged(boolean isRunning) {
        }

        @Override
        public void onGetLostSectorIdFailed() {

        }
    };

}

